package com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.useraction;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.example.dante.a17376060_wanghaikang_finaltest.R;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.MainActivity;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.adapter.NewsContentAdapter;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.broadcastReceiver.Receiver;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.domain.Name;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.domain.News;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.service.DownloadService;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.utils.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class NewsContent extends AppCompatActivity {
    public static final String NEWS_ID = "news_id";
    RecyclerView recyclerView;
    Integer news_id;
    String responseData;
    ImageView imageView;
    TextView textView2;
    List<Integer> sclist;
    String user_name;
    private List<News> newsList;
    private DownloadService.DownloadBinder downloadBinder;
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder= (DownloadService.DownloadBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    for (News news : newsList) {
                        String content = news.getNews_content();
                        Bitmap bitmap = (Bitmap) msg.obj;
                        imageView.setImageBitmap(bitmap);
                        textView2.setText(content);
                    }
                    break;
                case 2:
                    for (Integer sc : sclist) {
                        if (sc==1
                                ) {
                            Toast.makeText(getApplicationContext(), "新闻已收藏", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getApplicationContext(), "收藏失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_content);
        initView();
        Intent intent=new Intent(this,DownloadService.class);
        startService(intent);
        bindService(intent,connection,BIND_AUTO_CREATE);
        if(ContextCompat.checkSelfPermission(NewsContent.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(NewsContent.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }
        okhttp("http://47.101.175.33:8080/AndroidDataFinalTest/news_findById.action?news_id=" + news_id);
    }

    private void okhttp(final String address) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpUtil.sendOkHttpRequest(address, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        responseData = response.body().string();
                        parseJsonWithGsonObject(responseData);
                    }
                });
            }
        }).start();
    }

    private void initView() {
        Intent intent = getIntent();
        String id = intent.getStringExtra(NEWS_ID);
        news_id = Integer.parseInt(id);
        Toolbar toolbar = findViewById(R.id.news_content_toolbar);
        textView2=findViewById(R.id.news_content);
        imageView=findViewById(R.id.news_content_image);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                user_name = Name.USER_NAME;
                if (user_name != null) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            HttpUtil.sendOkHttpRequest("http://47.101.175.33:8080/AndroidDataFinalTest/user_shoucang.action?user_name=" + user_name + "&&news_id=" + news_id, new Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {

                                }

                                @Override
                                public void onResponse(Call call, Response response) throws IOException {
                                    responseData = response.body().string();
                                    Log.d("测试",responseData+"");
                                    parseJsonWithGsonSC(responseData);
                                }
                            });
                        }

                    }).start();
                }else {
                    Toast.makeText(getApplicationContext(),"尚未登录",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void parseJsonWithGsonSC(String responseData) {
        Gson gson = new Gson();
        sclist = gson.fromJson(responseData, new TypeToken<List<Integer>>() {
        }.getType());
        Message msg = new Message();
        msg.what = 2;
        handler.sendMessage(msg);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.download:
                if(downloadBinder!=null){
                    for(News news:newsList) {
                        Log.d("下载",news.getNews_txt());
                        downloadBinder.startDownload(news.getNews_txt());
                    }
                }
                break;
            default:
                break;
        }
        return true;
    }

    private void parseJsonWithGsonObject(String jsonData) {
        Gson gson = new Gson();
        newsList = gson.fromJson(jsonData, new TypeToken<List<News>>() {
        }.getType());
        for (News news : newsList) {
            Bitmap bmp = getURLimage(news.getNew_image());
            Message msg = new Message();
            msg.what = 1;
            msg.obj=bmp;
            handler.sendMessage(msg);
        }
    }

    private Bitmap getURLimage(String url) {
        Bitmap bmp = null;
        try {
            URL myurl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
            conn.setConnectTimeout(6000);
            conn.setDoInput(true);
            conn.setUseCaches(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bmp = BitmapFactory.decodeStream(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bmp;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length>0&&grantResults[0]!=PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this,"拒绝权限将无法使用",Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
                default:
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }
}
